<?php
declare (strict_types=1);

namespace app\model;

use think\Model;

/**
 * @mixin \think\Model
 */
class Questionnaire extends AppModel
{
    //
    const STATUS_ZERO = 0; //未同步
    const STATUS_ONE = 1; //已同步




    //关联问题类目表
    public function issueCategories(){
        return $this->hasMany(IssueCategory::class,'questionnaire_id')->field('id,issue_title,questionnaire_id');
    }


    public function questionInfo(){
        return $this->hasMany(QuestionInfo::class,'questionnaire_id');
    }

    /**
     * @param $arrData
     * @param $questionnaire_id
     * @User: 刘海龙
     * @Date: 2021/8/16
     * @Time: 17:23
     * @return bool
     * 问卷入库
     */
    public static function saveQuestionnaireArr($arrData, $questionnaire_id)
    {
        if (!empty($arrData)) {
            foreach ($arrData as $key => $value) {
                //新增类目表并获取类目表id
                $issue_category_id = IssueCategory::create([
                    'issue_title' => $value['issue_title'] ?? '',
                    'questionnaire_id' => $questionnaire_id ?? 0
                ])->id;
                if (isset($value['item'])) { //判断是否包含item字段
                    //如果包含item字段 循环
                    foreach ($value['item'] as $child_key => $child_value) {
                        //保存到问题表中并且获取对应的id
                        $question_id = IssueQuestion::create([
                            'issue_question_title' => $child_value['issue_question_title'] ?? '',
                            'issue_question_type' => IssueQuestion::$issue_question_type_arr[trim($child_value['issue_question_type'])] ?? 0, //需要转义下！
                            'issue_category_id' => $issue_category_id ?? 0,
                            'questionnaire_id' => $questionnaire_id ?? 0
                        ])->id;
                        //判断答案子节点是否包含item
                        if (isset($child_value['item'])) {
                            foreach ($child_value['item'] as $child_child_key => $child_child_value) {
                                IssueQuestionAnswer::create([
                                    'issue_answer_title' => $child_child_value['issue_answer_title'] ?? '',
                                    'issue_answer_type' => IssueQuestionAnswer::$issue_answer_type_arr[trim($child_child_value['issue_answer_type'])] ?? 0,
                                    'is_write' => IssueQuestionAnswer::$is_write_arr[trim($child_child_value['is_write'])] ?? 0,
                                    'issue_category_id' => $issue_category_id ?? 0,
                                    'issue_question_id' => $question_id ?? 0,
                                    'questionnaire_id' => $questionnaire_id ?? 0
                                ]);
                            }
                        }
                    }
                }
            }
            return true;
        } else {
            return false;
        }
    }
}
